package com.andnnl.list;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.json.JSONUtil;

import java.util.*;
import java.util.stream.Collectors;

/**
 * Created by chenss on 2021/11/19.
 */
public class ListDistinctTest {
    public static void main(String[] args) {
        HashMap<Integer, List<String>> priceMap = new HashMap<>();
        priceMap.put(202101,new ArrayList<>());
        priceMap.put(201807,new ArrayList<>());
        priceMap.put(202111,new ArrayList<>());
        priceMap.put(0,new ArrayList<>());
        Integer[] keys = priceMap.keySet().toArray(new Integer[priceMap.keySet().size()]);

        List<Integer> yearMonthList = new ArrayList<Integer>(Arrays.asList(keys));
        System.out.println(yearMonthList);
        Collections.sort(yearMonthList);//排序
        Collections.reverse(yearMonthList);//倒序
        System.out.println(yearMonthList);

//		logger.info(yearMonthList);

        //去除List中重复的String
        List<String> list = Arrays.asList("1", "2", "3", "2");
        List uniqueStr = list.stream().distinct().collect(Collectors.toList());
        System.out.println(uniqueStr);

        // Person 对象

        // 根据name去重
        List<Person> persons = new ArrayList<>();
        persons.add(new Person("1", "name1"));
        persons.add(new Person("2", "name1"));
        persons.add(new Person("3", "name3"));

        //无法去重
        List uniqueBe = persons.stream().distinct().collect(Collectors.toList());
        System.out.println(JSONUtil.toJsonStr(uniqueBe));
        Set<Person> nameSet = new HashSet<>(persons);
        System.out.println("实现equals和hashCode去重");
        System.out.println(JSONUtil.toJsonStr(nameSet));

        //按属性去重
        List<Person> unique = persons.stream().collect(
                Collectors.collectingAndThen(
                        Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(Person::getName))), ArrayList::new)
        );
        System.out.println("按属性去重");
        System.out.println(JSONUtil.toJsonStr(unique));
// 根据name,sex两个属性去重
        List<Person> unique2 = persons.stream().collect(
                Collectors.collectingAndThen(
                        Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(o -> o.getName() + ";" + o.getSex()))), ArrayList::new)
        );

        List<HashMap> lm = unique.stream().map((Person p) -> new HashMap<String,Object>(2) {{
            put("key", p.getName());
            put("value", p.getId());
        }}).collect(Collectors.toList());
        System.out.println(JSONUtil.toJsonStr(lm));

    }

}
